<template>
    <div class="category-page">
        <div class="page-body">
            <div class="cw-toolbar border-radius-tl border-radius-tr bg-white">
                <el-button type="primary" size="medium" @click="edit('add')">
                    <i class="ion ion-plus"></i>
                    <span>添加分类</span>
                </el-button>
            </div>
            <div class="category-page-body" v-loading="treeLoading">
                <el-tree v-show="treeShow" class="category-page-tree" ref="catsTree" highlight-current :data="categoryTree" :props="treeProps" node-key="id" default-expand-all :render-content="renderContent" :expand-on-click-node="false" empty-text="暂未分类，请先添加分类">
                </el-tree>
            </div>
            <el-dialog :title="dialogTitle" :visible.sync="addFormVisible" :close="clearForm">
                <el-form ref="catForm" :model="catFormData" :rules="rules" @keyup.enter.native="catFormSubmit('catForm')">
                    <el-form-item label="选择上级分类" :label-width="formLabelWidth">
                        <el-select v-model="catFormData.parent_id" placeholder="选择分类">
                            <el-option v-for="item in categorySelect" :key="item.id" :label="item.title" :style="selectOptStyle(item)" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="分类名称" prop="title" :label-width="formLabelWidth">
                        <el-input v-model="catFormData.title" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="选择分类模型" :label-width="formLabelWidth">
                        <el-select v-model="catFormData.model_id" placeholder="选择分类">
                            <el-option label="文章" value="1"></el-option>
                            <el-option label="图片" value="2"></el-option>
                            <el-option label="单页" value="3"></el-option>
                            <el-option label="下载" value="4"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button size="medium" @click="resetForm('catForm')">取 消</el-button>
                    <el-button size="medium" type="primary" @click="catFormSubmit('catForm')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
export default {
    name: 'Category',
    data() {
        return {
            formLabelWidth: '120px',
            editMode: '',
            addFormVisible: false,
            treeLoading: true,
            treeShow: false,
            categoryData: [],
            categoryTree: [],
            categoryObj: {},
            categorySelect: [],
            treeProps: {
                children: 'children',
                label: 'title'
            },
            catFormData: {
                parent_id: 0,
                model_id: '1',
                title: '',
                path: ''
            },
            rules: {
                parent_id: [
                    { required: true, message: '请选择上级分类', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请填写分类名称', trigger: 'blur' }
                ],
                model_id: [
                    { required: true, message: '请选择分类模型', trigger: 'change' }
                ]
            }
        };
    },
    computed: {
        categoryTreeData() {
            return this.getTree(this.categoryData);
        },
        dialogTitle() {
            return this.editMode === 'edit' ? '编辑分类' : '添加分类';
        }
    },
    methods: {
        // 获取栏目分类
        getCats() {
            this.whaleXHR.GET('/category').then(res => {
                if (res.code === 'success') {
                    this.categoryData = res.data;
                    let categoryTree = this.getTree(res.data),
                        catArr = [categoryTree];
                    this.categorySelect = [];
                    this.categoryObj = {};
                    this.getSelect(catArr);
                    this.categoryTree = categoryTree.children;
                }
                this.treeLoading = false;
                this.treeShow = true;
            });
        },
        getSelect(data) {
            for (let i = 0; i < data.length; i++) {
                this.categorySelect.push({
                    id: data[i].id,
                    title: data[i].title,
                    level: data[i].path.split(',').length
                });

                this.categoryObj[data[i].id] = data[i];

                if (data[i].children) {
                    if (data[i].children.length > 0) {
                        this.getSelect(data[i].children);
                    }
                }
            }
        },
        getTree(data) {
            let obj = {};
            if (data.length === 0) {
                return {
                    id: 0,
                    title: '顶级分类',
                    children: [],
                    path: '-1'
                };
            }

            for (let i = 0; i < data.length; i++) {
                if (!obj[data[i].parent_id]) {
                    obj[data[i].parent_id] = {};
                    obj[data[i].parent_id].children = [];
                }
                obj[data[i].parent_id].children.push(data[i]);
            }
            obj[0].title = '顶级分类';
            obj[0].id = 0;
            obj[0].path = '-1';
            for (const k in obj) {
                if (obj.hasOwnProperty(k)) {
                    let children = obj[k].children;
                    if (!children) return;
                    for (let i = 0; i < children.length; i++) {
                        if (obj.hasOwnProperty(children[i].id)) {
                            children[i].children = obj[children[i].id].children;
                        }
                    }
                }
            }

            return obj[0];
        },
        catFormSubmit(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let path = this.categoryObj[this.catFormData.parent_id]
                        .path;
                    this.catFormData.path = path
                        ? path + ',' + this.catFormData.parent_id
                        : '0';
                    if (this.editMode !== 'edit') {
                        this.whaleXHR
                            .POST('/category', this.catFormData)
                            .then(res => {
                                this.afterSubmit(res.code, formName);
                            });
                    } else {
                        this.whaleXHR
                            .PUT(
                                '/category/' + this.catFormData.id,
                                this.catFormData
                            )
                            .then(res => {
                                this.afterSubmit(res.code, formName);
                            });
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        afterSubmit(resStatus, formName) {
            if (resStatus === 'success') {
                this.resetForm(formName);
                this.$message({
                    message: this.dialogTitle + '成功',
                    type: 'success',
                    duration: 1000
                });
                this.getCats();
            }
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.addFormVisible = false;
        },
        edit(mode, data) {
            this.addFormVisible = true;
            this.editMode = mode;
            console.log(data);
            if (this.editMode === 'edit') {
                this.catFormData = {
                    parent_id: data.parent_id,
                    title: data.title,
                    path: data.path,
                    model_id: data.model_id.toString(),
                    id: data.id
                };
            } else if (this.editMode === 'append') {
                this.catFormData = {
                    parent_id: data.id,
                    title: '',
                    model_id: '1'
                };
            }
        },
        remove(node, data) {
            if (data.children) {
                if (data.children.length > 0) {
                    this.$message({
                        message: '该分类下有子分类，请先删除子分类',
                        type: 'warning'
                    });
                    return;
                }
            }

            this.$confirm('确定要删除该分类吗？', '提醒', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.del(node, data);
                })
                .catch(() => {});
        },
        del(node, data) {
            this.whaleXHR.DELETE('/category/' + data.id).then(res => {
                if (res.code === 'success') {
                    this.$message({
                        message: '删除分类成功',
                        type: 'success',
                        duration: 1000
                    });
                    this.getCats();
                }
            });
        },
        cancelDel(node, data) {},
        // 列表渲染
        renderContent(h, { node, data, store }) {
            return (
                <div cw-role="cell" cw-layout="fit">
                    <div
                        cw-role="cell"
                        cw-layout="fit"
                        cw-valign="middle"
                        class="cate-name"
                    >
                        {node.label}
                    </div>
                    <div cw-role="cell">
                        <el-button
                            class="font-12"
                            type="text"
                            on-click={() => this.edit('edit', data)}
                        >
                            编辑
                        </el-button>
                        <el-button
                            class="font-12"
                            type="text"
                            on-click={() => this.edit('append', data)}
                        >
                            添加子分类
                        </el-button>
                        <el-button
                            class="font-12 margin-r-8"
                            type="text"
                            on-click={() => this.remove(node, data)}
                        >
                            删除
                        </el-button>
                    </div>
                </div>
            );
        },
        // select option 缩进
        selectOptStyle(item) {
            return {
                'padding-left': item.level * 8 + 'px'
            };
        },
        // 清空表单
        clearForm() {
            this.catFormData = {
                parent_id: 0,
                model_id: '1',
                title: '',
                path: ''
            };
        }
    },
    mounted() {
        this.getCats();
    }
};
</script>

<style lang="scss" src="./style.scss"></style>

